package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseRecyclerViewAdapter;
import com.beiing.tianshuai.tianshuai.interest.entity.InterestVideoDetailBean;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.EmotionUtils;
import com.beiing.tianshuai.tianshuai.util.SpanStringUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.qmuiteam.qmui.span.QMUITouchableSpan;
import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;

/**
 * Created by Jinni on 2017/11/20 0020
 */

public class InterestVideoDetailReplyAdapter extends BaseRecyclerViewAdapter<InterestVideoDetailBean.DataBean.VideoCommentBean> {

    private static final String TABLE_TYPE_COMMENT = "0";
    private static final String TABLE_TYPE_REPLY = "2";

    private Context mContext;

    private OnUpClickListener mListener;

    private OnItemClickListener mItemClickListener;

    private OnAvatarClickListener mAvatarClickListener;

    private OnUsernameReplyToClickListener mOnUsernameReplyToClickListener;

    public InterestVideoDetailReplyAdapter(Context context) {
        mContext = context;
    }

    public void setListener(OnUpClickListener listener) {
        mListener = listener;
    }

    public void setItemClickListener(OnItemClickListener itemClickListener) {
        mItemClickListener = itemClickListener;
    }

    public void setAvatarClickListener(OnAvatarClickListener avatarClickListener) {
        mAvatarClickListener = avatarClickListener;
    }

    public void setOnUsernameReplyToClickListener(OnUsernameReplyToClickListener onUsernameReplyToClickListener) {
        mOnUsernameReplyToClickListener = onUsernameReplyToClickListener;
    }

    @Override
    public int getItemViewType(int position) {
        String tableType = mList.get(position).getTableType();
        switch (tableType) {
            case TABLE_TYPE_COMMENT:
                return 0;
            case TABLE_TYPE_REPLY:
                return 2;
        }
        return super.getItemViewType(position);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder result = null;
        switch (viewType) {
            case 0:
                result = new VideoReplyViewHolder(View.inflate(mContext, R.layout.item_video_common_reply, null));
                break;
            case 2:
                result = new VideoCommentReplyViewHolder(View.inflate(mContext, R.layout.item_video_common_reply, null));
                break;
        }
        return result;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof VideoReplyViewHolder) {
            InterestVideoDetailBean.DataBean.VideoCommentBean bean = mList.get(position);
            ((VideoReplyViewHolder) holder).setData(bean);
            ((VideoReplyViewHolder) holder).setListener(bean);
        } else if (holder instanceof VideoCommentReplyViewHolder) {
            InterestVideoDetailBean.DataBean.VideoCommentBean bean = mList.get(position);
            ((VideoCommentReplyViewHolder) holder).setData(bean);
            ((VideoCommentReplyViewHolder) holder).setListener(bean);
        }
    }

    class VideoReplyViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.civ_user_avatar)
        CircleImageView mUserAvatar;
        @BindView(R.id.tv_user_name)
        TextView mUserNickname;
        @BindView(R.id.tv_reply_content)
        QMUISpanTouchFixTextView mReplyContent;
        @BindView(R.id.tv_reply_university)
        TextView mReplierUniversity;
        @BindView(R.id.tv_reply_time)
        TextView mReplyTime;
        @BindView(R.id.tv_reply_up)
        TextView mTvReplyUp;

        VideoReplyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        public void setData(InterestVideoDetailBean.DataBean.VideoCommentBean bean) {
            // 发表者昵称
            mUserNickname.setText(bean.getName());
            // 发表者头像
            RequestOptions avatarOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .override(200, 200);
            String photo = bean.getPhoto();
            Glide.with(mContext.getApplicationContext())
                    .load(TextUtils.isEmpty(photo) ? R.mipmap.default_avatar : HttpRequestConstant.USER_PIC_HEAD + photo)
                    .apply(avatarOptions)
                    .into(mUserAvatar);
            // 作者学校
            mReplierUniversity.setText(bean.getUnit());
            // 评论内容
            try {
                String contentDecode = URLDecoder.decode(bean.getContent(), "UTF-8");
                mReplyContent.setText(SpanStringUtils.getEmotionContent(mContext, mReplyContent, contentDecode));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 发布评论的时间
            String replyTime = DateUtil.getTime(bean.getCreateTime());
            mReplyTime.setText(replyTime);
            // 根据评论的点赞状态设置drawable
            Drawable isThingDrawable;
            switch (bean.getVideoCommentThing()) {
                case 0:
                    isThingDrawable = mContext.getResources().getDrawable(
                            R.drawable.ic_comment_up
                    );
                    isThingDrawable.setBounds(0, 0, isThingDrawable.getMinimumWidth(),
                            isThingDrawable.getMinimumHeight());
                    mTvReplyUp.setCompoundDrawables(
                            null,
                            null,
                            isThingDrawable,
                            null);
                    break;
                default:
                    isThingDrawable = mContext.getResources().getDrawable(
                            R.drawable.ic_video_up_checked
                    );
                    isThingDrawable.setBounds(0, 0, isThingDrawable.getMinimumWidth(),
                            isThingDrawable.getMinimumHeight());
                    mTvReplyUp.setCompoundDrawables(
                            null,
                            null,
                            isThingDrawable,
                            null
                    );
                    break;
            }
            // 设置点赞数量
            mTvReplyUp.setText(bean.getThing());
        }

        public void setListener(final InterestVideoDetailBean.DataBean.VideoCommentBean bean) {
            mTvReplyUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onUpClickListener(v, bean);
                    }
                }
            });

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mItemClickListener != null) {
                        mItemClickListener.onItemClick(mReplyContent, bean, getAdapterPosition());
                    }
                }
            });

            mUserAvatar.setOnClickListener(new BGAOnNoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    if (mAvatarClickListener != null) {
                        mAvatarClickListener.onAvatarClick(bean, getAdapterPosition());
                    }
                }
            });
        }
    }

    class VideoCommentReplyViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.civ_user_avatar)
        CircleImageView mUserAvatar;
        @BindView(R.id.tv_user_name)
        TextView mUserNickname;
        @BindView(R.id.tv_reply_content)
        QMUISpanTouchFixTextView mReplyContent;
        @BindView(R.id.tv_reply_university)
        TextView mReplierUniversity;
        @BindView(R.id.tv_reply_time)
        TextView mReplyTime;
        @BindView(R.id.tv_reply_up)
        TextView mTvReplyUp;

        VideoCommentReplyViewHolder(View convertView) {
            super(convertView);
            ButterKnife.bind(this, convertView);
        }

        public void setData(final InterestVideoDetailBean.DataBean.VideoCommentBean bean) {

            // 发表者昵称
            mUserNickname.setText(bean.getName());

            // 发表者头像
            RequestOptions avatarOptions = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .override(200, 200);
            String photo = bean.getPhoto();
            Glide.with(mContext.getApplicationContext())
                    .load(TextUtils.isEmpty(photo) ? R.mipmap.default_avatar : HttpRequestConstant.USER_PIC_HEAD + photo)
                    .apply(avatarOptions)
                    .into(mUserAvatar);

            // 作者学校
            mReplierUniversity.setText(bean.getUnit());

            // 评论内容
            try {
                StringBuilder content = new StringBuilder();
                final String replyToName = "回复 " + bean.getUserName() + " : ";
                content.append(replyToName).append(URLDecoder.decode(bean.getContent(), "UTF-8"));
                SpannableString spannableString = new SpannableString(content.toString());

                //表情拼接
                Resources res = mContext.getResources();
                String regexEmotion = "\\[([\u4e00-\u9fa5\\w+\\.])+\\]";
                Pattern patternEmotion = Pattern.compile(regexEmotion);
                Matcher matcherEmotion = patternEmotion.matcher(content);
                while (matcherEmotion.find()){
                    // 获取匹配到的具体字符
                    String key = matcherEmotion.group();
                    // 匹配字符串的开始位置
                    int start = matcherEmotion.start();
                    // 利用表情名字获取到对应的图片
                    Integer imgRes = EmotionUtils.getImgByName(key);
                    if (imgRes != null) {
                        // 压缩表情图片
                        int size = (int) mReplyContent.getTextSize() * 13 / 10;
                        Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                        Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                        ImageSpan span = new ImageSpan(mContext, scaleBitmap);
                        spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }

                int highlightBgNormalColor = Color.parseColor("#00B2B2B2");
                int highlightBgPressedColor = Color.parseColor("#B0B2B2B2");

                // 为回复对象的昵称设置点击事件进入用户的个人主页
                spannableString.setSpan(new QMUITouchableSpan(
                        Color.parseColor("#B2B2B2"),
                        Color.parseColor("#B2B2B2"),
                        highlightBgNormalColor, highlightBgPressedColor) {
                    @Override
                    public void onSpanClick(View widget) {
                        if (mOnUsernameReplyToClickListener != null) {
                            mOnUsernameReplyToClickListener.onUsernameReplyToClick(widget, bean);
                        }
                    }
                }, 0, replyToName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                // 回复内容设置点击事件进行回复
                spannableString.setSpan(new QMUITouchableSpan(
                        Color.parseColor("#333333"),
                        Color.parseColor("#333333"),
                        highlightBgNormalColor, highlightBgPressedColor) {
                    @Override
                    public void onSpanClick(View widget) {
                        mItemClickListener.onItemClick(mReplyContent, bean, getAdapterPosition());
                    }
                }, replyToName.length(), content.toString().length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                mReplyContent.setMovementMethodDefault();
                mReplyContent.setText(spannableString);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // 发布评论的时间
            String replyTime = DateUtil.getTime(bean.getCreateTime());
            mReplyTime.setText(replyTime);

            // 根据评论的点赞状态设置drawable
            Drawable isThingDrawable;
            switch (bean.getVideoReplyThing()) {
                case 0:
                    isThingDrawable = mContext.getResources().getDrawable(
                            R.drawable.ic_comment_up
                    );
                    isThingDrawable.setBounds(0, 0, isThingDrawable.getMinimumWidth(),
                            isThingDrawable.getMinimumHeight());
                    mTvReplyUp.setCompoundDrawables(
                            null,
                            null,
                            isThingDrawable,
                            null);
                    break;
                default:
                    isThingDrawable = mContext.getResources().getDrawable(
                            R.drawable.ic_video_up_checked
                    );
                    isThingDrawable.setBounds(0, 0, isThingDrawable.getMinimumWidth(),
                            isThingDrawable.getMinimumHeight());
                    mTvReplyUp.setCompoundDrawables(
                            null,
                            null,
                            isThingDrawable,
                            null
                    );
                    break;
            }

            // 设置点赞数量
            mTvReplyUp.setText(bean.getThing());
        }

        public void setListener(final InterestVideoDetailBean.DataBean.VideoCommentBean bean) {
            mTvReplyUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onUpClickListener(v, bean);
                    }
                }
            });

            mUserAvatar.setOnClickListener(new BGAOnNoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    if (mAvatarClickListener != null) {
                        mAvatarClickListener.onAvatarClick(bean, getAdapterPosition());
                    }
                }
            });
        }
    }

    /**
     * 点赞按钮接口
     */
    public interface OnUpClickListener {
        void onUpClickListener(View v, InterestVideoDetailBean.DataBean.VideoCommentBean bean);
    }

    /**
     * item点击事件接口
     */
    public interface OnItemClickListener {
        void onItemClick(TextView view, InterestVideoDetailBean.DataBean.VideoCommentBean bean, int position);
    }

    /**
     * 头像点击事件接口
     */
    public interface OnAvatarClickListener {
        void onAvatarClick(InterestVideoDetailBean.DataBean.VideoCommentBean bean, int position);
    }

    /**
     * 回复内容中目标用户名点击事件
     */
    public interface OnUsernameReplyToClickListener {
        void onUsernameReplyToClick(View v, InterestVideoDetailBean.DataBean.VideoCommentBean bean);
    }
}

